package com.fourfinance.model.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fourfinance.model.dao.ClientDAO;
import com.fourfinance.model.domain.Client;

@Repository
public class ClientDAOImpl implements ClientDAO {

	@Autowired
	private SessionFactory sessionFactory;

	public Long add(Client client) {
		return (Long) sessionFactory.getCurrentSession().save(client);
	}

	public List<Client> list() {
		return sessionFactory.getCurrentSession().createQuery("from Client").list();
	}

	public void remove(Long id) {
		Client client = (Client) sessionFactory.getCurrentSession().load(Client.class, id);
		if (null != client) {
			sessionFactory.getCurrentSession().delete(client);
		}
	}
	
	public void removeAll() {
		sessionFactory.getCurrentSession().createQuery("delete from Client");
	}

	@Override
	public Client get(Long id) {
		return (Client) sessionFactory.getCurrentSession().get(Client.class, id);
	}

	@Override
	public Client getByFirstname(String firstName) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Client where firstname = :firstname");
		query.setParameter("firstname", firstName);
		return (Client) query.uniqueResult();
	}

	@Override
	public Client getByEmail(String email) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Client where email = :email");
		query.setParameter("email", email);
		return (Client) query.uniqueResult();
	}

	@Override
	public void remove(String email) {
		Query query = sessionFactory.getCurrentSession().createQuery("delete from Client where email = :email");
		query.setParameter("email", email);
		query.executeUpdate();
	}	
	
}
